package com.atguigu.guli.service.edu.controller.admin;


import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.service.edu.entity.Video;
import com.atguigu.guli.service.edu.feign.VodFileService;
import com.atguigu.guli.service.edu.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author liujun
 * @since 2021-01-20
 */
//@CrossOrigin
@Api(description = "视频管理")
@Slf4j
@RestController
@RequestMapping("/admin/edu/video")
public class VideoController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private VodFileService vodFileService;
    @ApiOperation("新增视频")
    @PostMapping("/save")
    public R save(
            @ApiParam(value="视频对象", required = true)
            @RequestBody Video video){
        boolean result = videoService.save(video);
        if (result) {
            return R.ok().message("保存成功");
        } else {
            return R.error().message("保存失败");
        }
    }

    @ApiOperation("删除视频")
    @DeleteMapping("/remove/{id}")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(
            @ApiParam(value="视频id", required = true)
            @PathVariable(value = "id") String id){
        final Video video = videoService.getById(id);
        if(video!=null && video.getVideoSourceId()!=null){
            //todo 删除视频中的视频
            vodFileService.removeVideo(video.getVideoSourceId());
        }
        //删除视频
        final boolean res = videoService.removeById(id);
        if (res) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }
    @ApiOperation("根据id查找视频")
    @GetMapping("/get/{id}")
    public R getById(
            @ApiParam(value="视频id", required = true)
            @PathVariable(value = "id") String id){
        final Video video = videoService.getById(id);
        if (video !=null) {
            return R.ok().data("item",video).message("查找成功");
        } else {
            return R.error().message("查找失败");
        }
    }

    @ApiOperation("更新视频")
    @PutMapping("/update")
    public R updateById(
            @ApiParam(value="视频", required = true)
            @RequestBody Video video){
        final boolean res = videoService.updateById(video);
        if (res) {
            return R.ok().message("更新成功");
        } else {
            return R.error().message("更新失败");
        }
    }
}

